import { ElMessage } from "element-plus";

/**
 * 提取 fetch options中 body header code的处理
 * 
 */

interface Options extends Omit<RequestInit, 'body'> {
    //  body?:{
    //     [name:string]:any
    // }
    body?: Record<string, any>
}

const baseUrl = "http://140.246.58.4:8090"

export default function request(url: string, options: Options = {}): Promise<any> {
    const { body, ...rest } = options
    //除body外，所有参数
    const fetchOptions: RequestInit = {
        ...rest,
    }
    //当method 为post 或其他类型时
    if (options.method && options.method.toUpperCase() !== 'GET') {
        //添加body 为外部传进来数据
        fetchOptions.body = JSON.stringify(body || {})
        //header
        fetchOptions.headers = {
            'Content-Type': 'application/json',
    
        }
    }
    //当method为get类型时
    fetchOptions.headers = {
        //克隆数据，当method为post时，需要token 需克隆header content-type
        ...(fetchOptions.headers || {}),
        authorization: localStorage.token,
       
    }

    return fetch(baseUrl + url, fetchOptions)
        .then(response => {
            console.log('response', response);
            if (response) {
                switch (response.status) {
                    case 401:
                        localStorage.clear();
                        window.localStorage.pathName='/login'
                        ElMessage.error('服务器错误')
                        break;
                    case 200:
                        return response.json()
                    default:
                        return Promise.reject(response)
                }
            }
            return response.json()
        })
        .then((res) => {
            if (res.code === 200) {
                //接口正常
                return res;
            } else {
                ElMessage.error(res.message || "接口错误")
                //接口错误，走catch
                return Promise.reject(res)
            }
        })
}